<template>
    <view>
        <div class="player-blank">
            <div class="player-btn" @click="play" v-if="paused">
                <image src="../../../static/ic_pause.png"></image>
            </div>
            <div class="player-btn" @click="play" v-if="!paused">
                <image src="../../../static/ic_play.png"></image>
            </div>
            <div class="start-time">{{format(currentTime)}}</div>
            <slider :value="sliderVal" step="0.1" @change="moveSlider" @changing="moveSlidering" block-size="12" block-color="#FD453D" selected-color="#FD453D" style="z-index: auto;flex: 1; margin:0 auto;">
            </slider>
            <div class="end-time">{{format(durationTime)}}</div>
        </div>
    </view>
</template>

<script>
    export default {
        props: {
            dataObj: {
                type: Object,
                default: {}
            },
			playCode:{
				type: Number,
				default: 0
			},
			unload:{
				type: Boolean,
				default: false
			}
			
        },
        data() {
            return {
                audioContext: null,
                paused: true,
                durationTime: 0,
                currentTime: 0,
                sliderVal: 0,
				pauseUrl:'',
				dragFlag:false,
            }
        },
		watch:{//监听用户点击播放的数据变动
			playCode: {
			    handler:function (item) {
							// console.log('音频地址',item)
							// console.log('播放的是否相等',this.playCode,this.dataObj.recordId)
					if (this.audioContext&&this.playCode!=this.dataObj.recordId) {
						// console.log('音频地址不相等',this.dataObj)
						this.paused=true
						this.audioContext.stop();
						this.sliderVal=0
						this.currentTime=0
						// this.audioContext.destroy()
					}
			    },
			    deep:true,//深度监听
				immediate:true,
			},
		},
		beforeDestroy() {
			console.log('销毁')
		    // 销毁组件时取消监听
			if (this.audioContext) {
				this.paused=true
				this.audioContext.pause();
				this.audioContext.destroy()
				this.audioContext=null
			}
		    // uni.$off('pageA:leave', this.handlePageLeave);
		    // uni.$off('pageA:enter', this.handlePageEnter);
		  },
		created() {
		  	this.audioContext = uni.createInnerAudioContext()
		  	this.audioContext.sessionCategory = 'soloAmbient';//在后台时不播放，如有其他播放，会暂停其他播放（但在移动端h5中 后台不播放失效）
		},
        mounted() {
				this.init(true)	
				this.$bus.$on("send",(param)=>{
					this.audioContext && this.audioContext.pause()
				})
        },
        methods: {
            play() {
				this.$emit('playEvent',this.dataObj.recordId)
				this.dragFlag=true
				if (this.paused) {
					this.init()
					this.audioContext.play()
					
				} else {
					this.pauseUrl=this.dataObj.audioUrl
					this.audioContext.pause()

				}
              
            },
            // pause() {
            //     this.audioContext.pause()
            // },
            // 拖拽过程中
            moveSlidering() {
				// if (this.audioContext) {
					// this.audioContext.destroy()

				// }
				// this.init()
				this.dragFlag=true
				this.$emit('playEvent',this.dataObj.recordId)
				this.audioContext.play()
				
                
            },
            // 拖动滚动条
            moveSlider(percent) {
				this.audioContext.pause()
				this.$emit('playEvent',this.dataObj.recordId)
				this.dragFlag=true
				console.log('percent',percent,this.audioContext)
                this.currentTime = this.durationTime * percent.detail.value / 100 // percent.detail.value
            	this.audioContext.seek(this.currentTime)
                this.audioContext.play()
            },
            // 格式化时间
            format(interval) {
                interval = interval | 0
                const minute = this._pad(interval / 60 | 0)
                const second = this._pad(interval % 60)
                return `${minute}:${second}`
            },
            _pad(num, n = 2) {
                let len = num.toString().length
                while (len < n) {
                    num = '0' + num
                    len++
                }
                return num
            },
			init(type){
				this.$tip.loading()
				// console.log('暂停打印',this.pauseUrl,this.dataObj.audioUrl)
				// 如果播放的 暂停了 再继续播放 不重新赋值
				if (!this.audioContext||this.pauseUrl!=this.dataObj.audioUrl) {
					this.audioContext.src = this.dataObj.audioUrl
				}

				this.audioContext.onPlay(() => {
					// console.log('监听onPlay',type,this.dragFlag)
					this.$tip.loaded()
					if(!type||this.dragFlag){
						this.paused = false
					} 
				  
				});
				this.audioContext.onCanplay(() =>{

				})
				
				this.audioContext.onPause(() => {
					this.$tip.loaded()
						// console.log('监听onPause',type,this.dragFlag)
				   if(!type||this.dragFlag){
				   	 this.paused = true
				   } 
				})
				this.audioContext.onStop(() => {
					// console.log('监听onStop',type,this.dragFlag)
					this.$tip.loaded()
				   if(!type||this.dragFlag){
					this.paused = true
				   } 
				})
				this.audioContext.onTimeUpdate(() => {
					// console.log(this.audioContext,"|",this.audioContext.currentTime,"?",this.audioContext.duration)
					this.currentTime = this.audioContext.currentTime
					if(!this.durationTime){
						this.durationTime = this.audioContext.duration
					}
				    this.sliderVal =  this.currentTime / this.durationTime * 100;
				})
				this.audioContext.onSeeked((listener)=>{
					console.log('监听拖拽音频')
				})
				// 音频正常播放完毕
				this.audioContext.onEnded(() => {
					// 这个为了解决 播放完后 得时间进度 和总时间有误差 1秒左右方法，
					if(Math.floor(this.currentTime)!=this.durationTime){
						this.currentTime=this.durationTime
						this.paused = true
					}
					this.$tip.loaded()
					this.audioContext.stop()
					this.paused = true
				})
				
				this.$tip.loaded()
				//为了获取 音频时长
				if(type){
					// console.log('this.dataObj.audioUrl',this.dataObj)
					if(this.dataObj.audioUrl && this.dataObj.audioUrl.split('durationTime=').length>1){
						// console.log('this.dataObj.audioUrl',)
						this.durationTime=Math.floor((this.dataObj.audioUrl.split('durationTime=')[1].split('.mp3')[0]*1)/1000)
					}else{
						if(this.dataObj.audioTime){
							this.durationTime=this.dataObj.audioTime
						}else{
							setTimeout(() => {
							  this.audioContext.volume=0			//音量 
							  this.audioContext.play();
							  setTimeout(() => {
								this.audioContext.pause();
								this.audioContext.volume=1		//音量 
							  }, 500); // 延迟秒后执行pause()
							}, 100);
						}
							
					}
					
				}
				this.audioContext.onError((res) => {
					this.$tip.loaded()
					if(res.errCode=='-1'){
						this.pauseUrl=''
						this.play()
					}

				  console.log('错误',res.errMsg);
				  console.log('错误',res.errCode);
				  
				});	
				
			}
        }
    }
</script>

<style scoped lang="scss">
    @function torem($rpx){  //$rpx为需要转换的字号
        @return #{$rpx * 100 / 750 / 4}rem; 
    }
    .player-blank {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: torem(96);
        line-height: torem(96);
        margin-top: 20rpx;
        background-color: #F7F7F7;
        padding: 0 8px;
        .start-time {
            text-align: center;
            width: torem(120);
			color: #999999;
			font-size:torem(24) ;
        }
        .end-time {
            text-align: center;
            width: torem(120);
			color: #999999;
			font-size:torem(24) ;
        }
    }
    .player-btn {
        width: torem(54);
        height: torem(54);
        line-height: torem(54);
        image {
            width: 98%;
            height: 98%;
        }
    }
</style>
